package com.yt.order.listener;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yt.order.models.dto.WorkOrderInfoDTO;
import com.yt.order.models.service.IAutoDispatchService;
import com.yt.order.models.service.IWorkOrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 订单创建事件监听器
 * 监听新订单创建并触发自动分配流程
 */
@Slf4j
@Component
public class OrderCreationListener implements ApplicationListener<ContextRefreshedEvent> {

    @DubboReference
    private IAutoDispatchService autoDispatchService;
    
    @DubboReference
    private IWorkOrderInfoService workOrderInfoService;

    // 使用一个标记来确保只启动一次监听器
    private final AtomicBoolean started = new AtomicBoolean(false);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 确保在Spring容器完全初始化后启动监听器
        if (event.getApplicationContext().getParent() == null && started.compareAndSet(false, true)) {
            startListening();
        }
    }

    /**
     * 启动订单监听器
     */
    private void startListening() {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleWithFixedDelay(this::checkNewOrders, 0, 5, TimeUnit.SECONDS);
        log.info("订单创建监听器已启动");
    }

    /**
     * 检查新订单并触发自动分配
     */
    private void checkNewOrders() {
        try {
            log.debug("检查新订单...");
            
            // 查询最近5秒内创建的待分配订单
            Wrapper<WorkOrderInfoDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("status", 0); // 待分配状态
            
            // 计算5秒前的时间
            Date fiveSecondsAgo = new Date(System.currentTimeMillis() - 5000);
            wrapper.ge("create_time", fiveSecondsAgo);
            
            List<WorkOrderInfoDTO> newOrders = workOrderInfoService.selectList(wrapper);
            
            if (!newOrders.isEmpty()) {
                log.info("发现 {} 个新订单需要自动分配", newOrders.size());
                for (WorkOrderInfoDTO order : newOrders) {
                    // 触发自动派单流程
                    autoDispatchService.handleOrderCreated(order.getId());
                }
            }
        } catch (Exception e) {
            log.error("检查新订单时发生异常", e);
        }
    }
}